"""A simple client for OpenSearch with Geo extensions"""

import urllib2, urlparse, cgi
from lxml import etree
from urllib import urlencode
#parse description

ns = "{http://a9.com/-/spec/opensearch/1.1/}"

class Description():
    def __init__(self,url):
        self._baseurl = url
        self._urls = [] 
        try:
            request = urllib2.Request(url)
            fp = urllib2.urlopen(request)
            self._xml = fp.read()

        except urllib2.URLError, e:
            raise e 

        x = etree.fromstring(self._xml)
        for u in x.findall(ns+"Url"):   
            a = u.attrib
            a['baseurl'] = self._baseurl
            self._urls.append(Url(a))
 
    def urls():
        pass
        #think about parsing them

    def request(self,type):
        for u in self._urls:
            if type == u._type:
                r = Request(u)
                return r

    def types(self):
        return [u._type for u in self._urls] 

class Url():
    def __init__(self,props):
        print props['template']
        t = urlparse.urlsplit(props['template'])
        self._type = props['type']
        self._url = t[0]+'://'+t[1]+t.path
        self._params = cgi.parse_qs(t.query)
     
class Request(dict):
    """Form an OpenSearch request. Pass in a Url."""
    def __init__(self,template):    
        self._template = template
        for key in template._params.keys():
            self[key] = None         

    def info(self,param):
        if param in self._template._params:
            return self._template._params[param][0]
    
    def response(self):
        print self._template._url
        try:
            # GET request only.
            data = {}
            for k in self.keys(): 
                if self[k] is not None: data[k] = self[k]
            data = urlencode(data)
            request = urllib2.Request(self._template._url+'?'+data)
            fp = urllib2.urlopen(request)
            response = fp.read()
            return response

        except urllib2.URLError, e:
            raise e

# issue a request

#do stuff with results
